<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1700px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="150px"
      v-loading="formLoading"
      :disabled="disabled"
    >
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="基础信息" name="first">
          <el-row :gutter="60">
            <el-col :span="8">
              <el-form-item label="客户编号" prop="id">
                <el-input disabled v-model="formData.id" placeholder="系统自动生成" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系人" prop="contact">
                <el-input v-model="formData.contact" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="手机号码" prop="mobile">
                <el-input v-model="formData.mobile" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系电话" prop="telephone">
                <el-input v-model="formData.telephone" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="电子邮箱" prop="email">
                <el-input v-model="formData.email" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="传真" prop="fax">
                <el-input v-model="formData.fax" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="formData.remark" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开启状态" prop="status">
                <el-select v-model="formData.status" clearable placeholder="请选择">
                  <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="排序" prop="sort">
                <el-input v-model="formData.sort" placeholder="请输入排序" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="纳税人识别号" prop="taxNo">
                <el-input v-model="formData.taxNo" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="税率" prop="taxPercent">
                <el-input v-model="formData.taxPercent" placeholder="请输入">
                  <template #append>%</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开户行" prop="bankName">
                <el-input v-model="formData.bankName" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开户账号" prop="bankAccount">
                <el-input v-model="formData.bankAccount" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开户地址" prop="bankAddress">
                <el-input v-model="formData.bankAddress" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="领用状态" prop="receivingStatus">
                <el-switch v-model="formData.receivingStatus" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="企业联系电话" prop="enterprisePhone">
                <el-input v-model="formData.enterprisePhone" placeholder="请输入" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="网站对外展示电话" prop="websitePhone">
                <el-input v-model="formData.websitePhone" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户线索标签" prop="clueTags">
                <el-input v-model="formData.clueTags" placeholder="请输入" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="客户所属行业" prop="customerIndustry">
                <el-input v-model="formData.customerIndustry" placeholder="请输入" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="所在省份" prop="province">
                <el-input v-model="formData.province" placeholder="请输入" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="所在城市" prop="city">
                <el-input v-model="formData.city" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <!-- 
        <el-col :span="8">
          <el-form-item label="领用该客户的员工" prop="receiverId">
            <el-input v-model="formData.receiverId" placeholder="请输入" />
          </el-form-item>
        </el-col> -->

            <!-- <el-col :span="8">
          <el-form-item label="分配客户的员工" prop="assignerId">
            <el-input v-model="formData.assignerId" placeholder="请输入" />
          </el-form-item>
        </el-col> -->

            <el-col :span="8">
              <el-form-item label="客户分配时间" prop="assignmentDate">
                <el-date-picker
                  v-model="formData.assignmentDate"
                  type="date"
                  value-format="x"
                  placeholder="选择"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="注册资金" prop="registeredCapital">
                <el-input v-model="formData.registeredCapital" placeholder="请输入">
                  <template #append>元</template>
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="客户分类" prop="customerCategory">
                <el-select v-model="formData.customerCategory" clearable placeholder="请选择">
                  <el-option
                    v-for="item in customerCategoryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="客户来源" prop="customerSource">
                <el-select v-model="formData.customerSource" clearable placeholder="请选择">
                  <el-option
                    v-for="item in customerSourceOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="放弃客户的原因" prop="abandonmentReason">
                <el-input
                  v-model="formData.abandonmentReason"
                  type="textarea"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
            <!-- 
        <el-col :span="8">
          <el-form-item label="放弃客户的员工" prop="abandonerId">
            <el-input v-model="formData.abandonerId" placeholder="请输入" />
          </el-form-item>
        </el-col> -->

            <el-col :span="8">
              <el-form-item label="客户状态" prop="customerStatus">
                <el-select v-model="formData.customerStatus" clearable placeholder="请选择">
                  <el-option
                    v-for="item in customerStatusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="放弃客户时间" prop="abandonmentDate">
                <el-date-picker
                  v-model="formData.abandonmentDate"
                  type="date"
                  value-format="x"
                  placeholder="选择"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="公司注册地址" prop="companyAddress">
                <el-input v-model="formData.companyAddress" placeholder="请输入" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="公司法定代表人" prop="legalRepresentative">
                <el-input v-model="formData.legalRepresentative" placeholder="请输入" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="公司员工规模" prop="employeeCount">
                <el-input v-model="formData.employeeCount" placeholder="请输入" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="公司官方网站URL" prop="officialWebsite">
                <el-input v-model="formData.officialWebsite" placeholder="请输入" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="联系人姓名" prop="contactName">
                <el-input v-model="formData.contactName" placeholder="请输入）" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="性别" prop="gender">
                <el-select v-model="formData.gender" clearable placeholder="请选择">
                  <el-option
                    v-for="item in genders"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="联系人所属部门" prop="department">
                <el-input v-model="formData.department" placeholder="请输入" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="联系人职务" prop="position">
                <el-input v-model="formData.position" placeholder="请输入" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="联系人籍贯" prop="nativePlace">
                <el-input v-model="formData.nativePlace" placeholder="请输入" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="其他补充说明" prop="remarks">
                <el-input v-model="formData.remarks" type="textarea" placeholder="请输入" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="客户跟进记录次数" prop="followUpCount">
                <el-input-number
                  v-model="formData.followUpCount"
                  :min="1"
                  :max="10"
                  @change="handleChange"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="客户基本情况简介" prop="customerProfile">
                <el-input v-model="formData.customerProfile" type="textarea" placeholder="请输入" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="当前合作状态" prop="cooperationStatus">
                <el-input v-model="formData.cooperationStatus" placeholder="请输入" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="银行开户名称" prop="bankAccountName">
                <el-input
                  v-model="formData.bankAccountName"
                  placeholder="请输入银行开户名称（需与账户名一致）"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="合作洽谈阶段" prop="negotiationProgress">
                <el-select v-model="formData.negotiationProgress" clearable placeholder="请选择">
                  <el-option
                    v-for="item in negotiationProgressOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="线索来源" prop="clueCategory">
                <el-select v-model="formData.clueCategory" clearable placeholder="请选择">
                  <el-option
                    v-for="item in clueCategoryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <!-- <el-col :span="8">
          <el-form-item label="所属二级客户" prop="parentCustomerId">
            <el-input v-model="formData.parentCustomerId" placeholder="请输入" />
          </el-form-item>
        </el-col> -->

            <el-col :span="8">
              <el-form-item label="客户等级" prop="customerLevel">
                <el-select v-model="formData.customerLevel" clearable placeholder="请选择">
                  <el-option
                    v-for="item in customerLevelOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="所属地理区域" prop="region">
                <el-input
                  v-model="formData.region"
                  placeholder="请输入所属地理区域（如：华北、华东）"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <!-- <el-tab-pane label="结算账户" name="second">
          <el-form
            ref="formRef"
            :model="formData"
            :rules="formRules"
            label-width="100px"
            v-loading="formLoading"
          >
            <el-row :gutter="60">
                  <el-col :span="8">
            <el-form-item label="账户名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入账户名称" />
            </el-form-item>
            <el-form-item label="账户编码" prop="no">
              <el-input v-model="formData.no" placeholder="请输入账户编码" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" placeholder="请输入备注" />
            </el-form-item>
            <el-form-item label="开启状态" prop="status">
              <el-select v-model="formData.status" clearable placeholder="请选择" class="!w-240px">
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
                  </el-col>
                      <el-col :span="8">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="formData.sort" placeholder="请输入排序" />
            </el-form-item>
            <el-form-item label="是否默认" prop="defaultStatus">
              <el-select
                v-model="formData.defaultStatus"
                clearable
                placeholder="请选择"
                class="!w-240px"
              >
                <el-option
                  v-for="item in defaultStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
                      </el-col>
            </el-row>
          </el-form>
        </el-tab-pane> -->
      </el-tabs>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { CustomerApi, CustomerVO } from '@/api/erp/sale/customer'
import { StockApi, DictItemConfigVO } from '@/api/erp/stock/stock'
import type { TabsPaneContext } from 'element-plus'
/** ERP 客户 表单 */
defineOptions({ name: 'CustomerForm' })
const disabled = computed(() => formType.value === 'detail')
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const activeName = ref('first')
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  abandonerId: undefined,
  abandonmentDate: undefined,
  abandonmentReason: undefined,
  assignerId: undefined,
  assignmentDate: undefined,
  bankAccount: undefined,
  bankAccountName: undefined,
  bankAddress: undefined,
  bankName: undefined,
  city: undefined,
  clueCategory: undefined,
  clueTags: undefined,
  companyAddress: undefined,
  contact: undefined,
  contactName: undefined,
  cooperationStatus: undefined,
  createTime: undefined,
  customerCategory: undefined,
  customerIndustry: undefined,
  customerLevel: undefined,
  customerProfile: undefined,
  customerSource: undefined,
  customerStatus: undefined,
  department: undefined,
  email: undefined,
  employeeCount: undefined,
  enterprisePhone: undefined,
  fax: undefined,
  followUpCount: undefined,
  gender: undefined,
  id: undefined,
  legalRepresentative: undefined,
  mobile: undefined,
  name: undefined,
  nativePlace: undefined,
  negotiationProgress: undefined,
  officialWebsite: undefined,
  parentCustomerId: undefined,
  position: undefined,
  province: undefined,
  receiverId: undefined,
  receivingStatus: undefined,
  region: undefined,
  registeredCapital: undefined,
  remark: undefined,
  remarks: undefined,
  sort: undefined,
  status: undefined,
  taxNo: undefined,
  taxPercent: undefined,
  telephone: undefined,
  websitePhone: undefined
})
const formRules = reactive({
  name: [{ required: true, message: '客户名称不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '开启状态不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const genders = [
  {
    value: '男',
    label: '男'
  },
  {
    value: '女',
    label: '女'
  }
]
const statusOptions = ref<{ value: string; label: string }[]>([])
const customerStatusOptions = ref<{ value: string; label: string }[]>([])
const customerSourceOptions = ref<{ value: string; label: string }[]>([])
const clueCategoryOptions = ref<{ value: string; label: string }[]>([])
const customerLevelOptions = ref<{ value: string; label: string }[]>([])
const negotiationProgressOptions = ref<{ value: string; label: string }[]>([])
const customerCategoryOptions = ref<{ value: string; label: string }[]>([])

const getdictItemData = async () => {
  const data = {
    dictCode: 'customer_source'
  }
  const openStatus = { dictCode: 'status' }
  const cusStatus = { dictCode: 'customer_status' }
  const clueCategory = { dictCode: 'clue_category' }
  const customerLevel = { dictCode: 'customer_level' }
  const negotiationProgress = { dictCode: 'negotiation_progress' }
  const customerCategory = { dictCode: 'customer_category' }
  const openStatusRes = await StockApi.getByDictCode(openStatus)
  statusOptions.value = openStatusRes.map((item) => ({
    value: item.value,
    label: item.description
  }))
  const response = await StockApi.getByDictCode(data)
  customerSourceOptions.value = response.map((item) => ({
    value: item.value,
    label: item.description
  }))
  const statusRes = await StockApi.getByDictCode(cusStatus)
  customerStatusOptions.value = statusRes.map((item) => ({
    value: item.value,
    label: item.description
  }))
  const clueCategoryRes = await StockApi.getByDictCode(clueCategory)
  clueCategoryOptions.value = clueCategoryRes.map((item) => ({
    value: item.value,
    label: item.description
  }))
  const customerLevelRes = await StockApi.getByDictCode(customerLevel)
  customerLevelOptions.value = customerLevelRes.map((item) => ({
    value: item.value,
    label: item.description
  }))
  const negotiationProgressRes = await StockApi.getByDictCode(negotiationProgress)
  negotiationProgressOptions.value = negotiationProgressRes.map((item) => ({
    value: item.value,
    label: item.description
  }))
  const customerCategoryRes = await StockApi.getByDictCode(customerCategory)
  customerCategoryOptions.value = customerCategoryRes.map((item) => ({
    value: item.value,
    label: item.description
  }))
}
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type) + '客户'
  formType.value = type
  resetForm()
  getdictItemData()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CustomerApi.getCustomer(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  formLoading.value = true
  try {
    const data = formData.value as unknown as CustomerVO
    if (formType.value === 'create') {
      // 获取当前时间戳（13位）并转换为字符串
      const timestamp = Date.now().toString()
      // 取前12位作为ID（当前时间戳固定为13位，所以安全）
      formData.value.id = parseInt(timestamp.substring(0, 12))
      await CustomerApi.createCustomer(data)
      message.success(t('common.createSuccess'))
    } else {
      await CustomerApi.updateCustomer(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    abandonerId: undefined,
    abandonmentDate: undefined,
    abandonmentReason: undefined,
    assignerId: undefined,
    assignmentDate: undefined,
    bankAccount: undefined,
    bankAccountName: undefined,
    bankAddress: undefined,
    bankName: undefined,
    city: undefined,
    clueCategory: undefined,
    clueTags: undefined,
    companyAddress: undefined,
    contact: undefined,
    contactName: undefined,
    cooperationStatus: undefined,
    createTime: undefined,
    customerCategory: undefined,
    customerIndustry: undefined,
    customerLevel: undefined,
    customerProfile: undefined,
    customerSource: undefined,
    customerStatus: undefined,
    department: undefined,
    email: undefined,
    employeeCount: undefined,
    enterprisePhone: undefined,
    fax: undefined,
    followUpCount: undefined,
    gender: undefined,
    id: undefined,
    legalRepresentative: undefined,
    mobile: undefined,
    name: undefined,
    nativePlace: undefined,
    negotiationProgress: undefined,
    officialWebsite: undefined,
    parentCustomerId: undefined,
    position: undefined,
    province: undefined,
    receiverId: undefined,
    receivingStatus: undefined,
    region: undefined,
    registeredCapital: undefined,
    remark: undefined,
    remarks: undefined,
    sort: undefined,
    status: undefined,
    taxNo: undefined,
    taxPercent: undefined,
    telephone: undefined,
    websitePhone: undefined
  }
  formRef.value?.resetFields()
}
</script>
